package com.course02.order_backend.exception.Ost;

import com.course02.order_backend.common.Ost.Result;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 全局异常处理器，统一处理校验失败和业务异常
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 处理参数校验失败异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result handleValidationException(MethodArgumentNotValidException e) {
        BindingResult bindingResult = e.getBindingResult();
        // 获取第一个校验失败的信息
        FieldError firstError = bindingResult.getFieldErrors().get(0);
        return Result.error(firstError.getDefaultMessage());
    }

    /**
     * 处理用户名/手机号已存在异常
     */
    @ExceptionHandler(DuplicateException.class)
    public Result handleDuplicateException(DuplicateException e) {
        return Result.error(e.getMessage());
    }

    /**
     * 处理其他未知异常
     */
    @ExceptionHandler(Exception.class)
    public Result handleException(Exception e) {
        return Result.error("服务器内部错误：" + e.getMessage());
    }
}